package com.pig4cloud.pigx.contract.executer.k_line;

import com.alibaba.fastjson.JSONObject;
import com.pig4cloud.pigx.common.customize.exception.MqAckException;
import com.pig4cloud.pigx.contract.constant.ContractMqConstants;
import com.pig4cloud.pigx.contract.executer.k_line.canceler.KlineCanceler;
import com.pig4cloud.pigx.contract.mongo.entity.ContractKLineTradeCacheMongo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * k线执行器
 *
 * @since 2022/8/1p 10:54
 */
@Slf4j
@Component
@AllArgsConstructor
public class KLineExecutor {

    private final KlineCanceler canceler;

    /**
     * 监听 contract.init.trade 队列
     *
     * @since 2022/9/8 15:44:00
     */
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value = ContractMqConstants.QUEUE_FANOUT_CONTRACT_INIT_TRADE),
                    exchange = @Exchange(value = ContractMqConstants.EXCHANGE_FANOUT_CONTRACT_INIT_TRADE, type = ExchangeTypes.FANOUT)
            )})
    public void expire(String obj) {
        ContractKLineTradeCacheMongo mongo = JSONObject.parseObject(obj, ContractKLineTradeCacheMongo.class);
        log.info("{} 新增k线临时交易记录&币对最新成交。id：{}", this.getClass().getSimpleName(), mongo);
        try {
            canceler.initNewestTrade(mongo);
            canceler.initKlineTradeCache(mongo);
        } catch (MqAckException ignore) {
        }
    }
}
